//
//  SDHSportsDataManager.m
//  SDHSportsNews
//
//  Created by MichaelShan on 2021/3/9.
//

#import "SDHSportsDataManager.h"
#import "SDHSportsFileManager.h"
#import "SDHSportsNewsModal.h"
#import "SDHSportsMatchSoccerModel.h"
#import "SDHSportsTeamInfoModel.h"
#import "MJExtension.h"
#import "SDHSportsUserModel.h"

#define kUserInfoKey    @"user"
#define kNewsCacheKey   @"news"

@implementation SDHSportsDataManager
@synthesize user = _user;

static SDHSportsDataManager *_sharedManager = nil ;

+ (instancetype)sharedManager {
    @synchronized(self){
        if (_sharedManager == nil) {
            _sharedManager = [[SDHSportsDataManager alloc]  init];
        }
    }
    return _sharedManager;
}

// 防止外部调用alloc 或者 new
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    if (_sharedManager == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            _sharedManager = [super allocWithZone:zone];
        });
    }
    return _sharedManager;
}

- (id)copyWithZone:(NSZone *)zone {
    return [SDHSportsDataManager sharedManager];
}

- (id)mutableCopyWithZone:(NSZone *)zone {
    return [SDHSportsDataManager sharedManager];
}

- (id)init {
    if (self = [super init]) {
        _sharedManager = [SDHSportsDataManager sharedManager];
        _newsArray = [NSMutableArray array];
    }
    
    return self;
}

#pragma mark - cache
- (void)setUser:(SDHSportsUserModel *)user {
    _user = user;
    
    NSDictionary *dic = [user mj_keyValues];
    [[NSUserDefaults standardUserDefaults] setObject:dic forKey:kUserInfoKey];
}

- (SDHSportsUserModel *)user {
    if (_user == nil) {
        NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:kUserInfoKey];
        SDHSportsUserModel *user = [SDHSportsUserModel mj_objectWithKeyValues:dic];
        _user = user;
    }
    
    return _user;
}

- (void)addBrowseNews:(SDHSportsNewsModal *)model {
    if (model == nil) {
        return;
    }
    
    [self addNews:model toFile:kBrowseNewsDataKey];
}

- (void)addFollowNews:(SDHSportsNewsModal *)model {
    if (model == nil) {
        return;
    }
    
    [self addNews:model toFile:kFollowNewsDataKey];
}

- (NSArray *)getBrowseNews {
    NSString *filename = [self getFilename:kBrowseNewsDataKey];
    NSArray *array = [SDHSportsFileManager readArrayFromFileName:filename];
    NSArray *newsArr = [SDHSportsNewsModal mj_objectArrayWithKeyValuesArray:array];
    return newsArr;
}

- (NSArray *)getFollowNews {
    NSString *filename = [self getFilename:kFollowNewsDataKey];
    NSArray *array = [SDHSportsFileManager readArrayFromFileName:filename];
    NSArray *newsArr = [SDHSportsNewsModal mj_objectArrayWithKeyValuesArray:array];
    return newsArr;
}

- (void)addNews:(SDHSportsNewsModal *)model toFile:(NSString *)filename {
    if (model == nil) {
        return;
    }
    filename = [self getFilename:filename];
    
    NSArray *array = [SDHSportsFileManager readArrayFromFileName:filename];
    NSArray *newsArr = [SDHSportsNewsModal mj_objectArrayWithKeyValuesArray:array];
    BOOL alreadyExist = NO;
    for (SDHSportsNewsModal *tmpModel in newsArr) {
        if ([tmpModel.newsId isEqualToString:model.newsId]) {
            alreadyExist = YES;
            break;
        }
    }
    
    if (!alreadyExist) {
        if (newsArr == nil) {
            newsArr = @[];
        }
        NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:newsArr];
        [tmpArray addObject:model];
        
        NSArray *arraydata = [SDHSportsNewsModal mj_keyValuesArrayWithObjectArray:tmpArray];
        [SDHSportsFileManager saveArray:arraydata toFileName:filename];
    }
}

- (void)addBrowseMatch:(SDHSportsMatchSoccerModel *)model {
    [self addMatch:model toFile:kBrowseMatchDataKey];
}
- (void)addFollowMatch:(SDHSportsMatchSoccerModel *)model {
    [self addMatch:model toFile:kFollowMatchDataKey];
}

- (NSArray *)getBrowseMatch {
    NSString *filename = [self getFilename:kBrowseMatchDataKey];
    NSArray *array = [SDHSportsFileManager readArrayFromFileName:filename];
    NSArray *newsArr = [SDHSportsMatchSoccerModel mj_objectArrayWithKeyValuesArray:array];
    return newsArr;
}

- (NSArray *)getFollowMatch {
    NSArray *array = [SDHSportsFileManager readArrayFromFileName:kFollowMatchDataKey];
    NSArray *newsArr = [SDHSportsMatchSoccerModel mj_objectArrayWithKeyValuesArray:array];
    return newsArr;
}

- (void)addMatch:(SDHSportsMatchSoccerModel *)model toFile:(NSString *)filename {
    if (model == nil) {
        return;
    }
    
    filename = [self getFilename:filename];
    NSArray *array = [SDHSportsFileManager readArrayFromFileName:filename];
    NSArray *newsArr = [SDHSportsMatchSoccerModel mj_objectArrayWithKeyValuesArray:array];
    BOOL alreadyExist = NO;
    for (SDHSportsMatchSoccerModel *tmpModel in newsArr) {
        if ([tmpModel.matchId isEqualToString:model.matchId]) {
            alreadyExist = YES;
            break;
        }
    }
    
    if (!alreadyExist) {
        if (newsArr == nil) {
            newsArr = @[];
        }
        NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:newsArr];
        [tmpArray addObject:model];
        
        NSArray *arraydata = [SDHSportsMatchSoccerModel mj_keyValuesArrayWithObjectArray:tmpArray];
        [SDHSportsFileManager saveArray:arraydata toFileName:filename];
    }
}

- (void)addBrowseTeam:(SDHSportsTeamInfoModel *)model {
    [self addTeam:model toFile:kBrowseTeamDataKey];
}

- (void)addFollowTeam:(SDHSportsTeamInfoModel *)model {
    [self addTeam:model toFile:kFollowTeamDataKey];
}

- (NSArray *)getBrowseTeam {
    NSString *filename = [self getFilename:kBrowseTeamDataKey];
    NSArray *array = [SDHSportsFileManager readArrayFromFileName:filename];
    NSArray *newsArr = [SDHSportsTeamInfoModel mj_objectArrayWithKeyValuesArray:array];
    return newsArr;
}

- (NSArray *)getFollowTeam {
    NSString *filename = [self getFilename:kFollowTeamDataKey];
    NSArray *array = [SDHSportsFileManager readArrayFromFileName:filename];
    NSArray *newsArr = [SDHSportsTeamInfoModel mj_objectArrayWithKeyValuesArray:array];
    return newsArr;
}

- (void)addTeam:(SDHSportsTeamInfoModel *)model toFile:(NSString *)filename {
    if (model == nil) {
        return;
    }
    filename = [self getFilename:filename];
    
    NSArray *array = [SDHSportsFileManager readArrayFromFileName:filename];
    NSArray *newsArr = [SDHSportsTeamInfoModel mj_objectArrayWithKeyValuesArray:array];
    BOOL alreadyExist = NO;
    for (SDHSportsTeamInfoModel *tmpModel in newsArr) {
        if ([tmpModel.en_name isEqualToString:model.en_name]) {
            alreadyExist = YES;
            break;
        }
    }
    
    if (!alreadyExist) {
        if (newsArr == nil) {
            newsArr = @[];
        }
        NSMutableArray *tmpArray = [NSMutableArray arrayWithArray:newsArr];
        [tmpArray addObject:model];
        
        NSArray *arraydata = [SDHSportsTeamInfoModel mj_keyValuesArrayWithObjectArray:tmpArray];
        [SDHSportsFileManager saveArray:arraydata toFileName:filename];
    }
}

- (NSString *)getFilename:(NSString *)filename {
    NSString *fName = filename;
    if (self.user.phone.length > 0) {
        fName = [NSString stringWithFormat:@"%@-%@", _user.phone, filename];
    }
    return fName;
}

- (void)addNews:(NSArray *)newsArr {
    NSMutableDictionary *tmpDict = [NSMutableDictionary dictionary];
    for (SDHSportsNewsModal *model in _newsArray) {
        [tmpDict setObject:model forKey:model.newsId];
    }
    
    BOOL changed = NO;
    for (SDHSportsNewsModal *model in newsArr) {
        if ([tmpDict objectForKey:model.newsId] == nil) {
            [_newsArray addObject:model];
            changed = YES;
        }
    }
    
    if (changed) {
        NSArray *arraydata = [SDHSportsNewsModal mj_keyValuesArrayWithObjectArray:_newsArray];
        [SDHSportsFileManager saveArray:arraydata toFileName:kNewsCacheKey];
    }
}

- (void)clearCache {
    if (_user.phone.length > 0) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
            NSString *documents = [pathArray objectAtIndex:0];
            NSString *documnetPath = nil;
            NSFileManager *fm = [NSFileManager defaultManager];
            //取得一个目录下得所有文件名
            NSArray *files = [fm subpathsAtPath:documents];
            
            for (NSString *filename in files) {
                if ([filename hasPrefix:self.user.phone]) {
                    documnetPath = [documents stringByAppendingPathComponent:filename];
                    [fm removeItemAtPath:documnetPath error:nil];
                }
            }
        });
    }
}

- (void)logout {
    _user = nil;
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserInfoKey];
}

@end
